<template>
  <div class="tempbigbox">
    <div class="console">
      <CardList :top-Data="topData" :key="topKey"></CardList>
      <div class="column column2">
        <div class="page-content">
          <div class="header" style="margin-bottom: 1.5rem">
            <h3>用户列表</h3>
          </div>
          <el-form :model="searchForm" ref="searchFormRef" label-width="auto" style="padding-bottom: 1.5rem">
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="用户名：" prop="name">
                  <el-input placeholder="请输入用户名" v-model="searchForm.name" clearable @blur="getData"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="手机号：" prop="phone">
                  <el-input placeholder="请输入手机号" v-model="searchForm.phone" clearable @blur="getData"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="是否学员：" prop="queryApplyState">
                  <el-select v-model="searchForm.queryApplyState" placeholder="请选择是否学员" clearable @change="getData">
                    <el-option v-for="item in baomingOptions" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="是否VIP：" prop="level">
                  <el-select v-model="searchForm.level" placeholder="请选择是否VIP" clearable @change="getData">
                    <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="6">
                <div class="databox">
                  <label class="el-form-item__label">注册时间：</label>
                  <el-date-picker label="注册时间：" v-model="datavalue1" type="datetimerange" start-placeholder="开始日期"
                    end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                    time-format="A hh:mm:ss" @change="createTime" />
                </div>
              </el-col>
              <el-col :span="6">
                <div class="databox">
                  <label class="el-form-item__label">最近活跃时间：</label>
                  <el-date-picker label="创建时间：:" v-model="datavalue2" type="datetimerange" start-placeholder="开始日期"
                    end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                    time-format="A hh:mm:ss" @change="activeTime" />
                </div>
              </el-col>
            </el-row>
          </el-form>
          <ArtTable :data="tableData" selection :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize"
            :total="pageTotal" @current-change="currentChange" @size-change="sizeChange">
            <template #default>
              <el-table-column label="用户信息" prop="avatar" #default="scope" width="200px" v-if="columns[0].show"
                style="cursor: pointer">
                <div class="user" style="display: flex; align-items: center; cursor: pointer"
                  @click="linkuserdetails(scope.row.id)">
                  <img class="avatar" :src="scope.row.avatar" v-if="scope.row.avatar" />
                  <div>
                    <el-dropdown placement="top-end">
                      <el-link underline="never">{{ scope.row.nickName }}</el-link>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item>
                            <p>{{ scope.row.nickName }} ID:{{ scope.row.id }}</p>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <p class="email">ID:{{ scope.row.id }}</p>
                  </div>
                </div>
              </el-table-column>
              <el-table-column label="手机号" prop="mobile" v-if="columns[1].show" align="center" />
              <el-table-column label="关联学员" prop="realName" v-if="columns[1].show" align="center" />
              <el-table-column label="所学车型" prop="carModelName" v-if="columns[1].show" align="center" />
              <el-table-column label="移动端报名" prop="isSignUpStore" v-if="columns[4].show" align="center">
                <template #default="scope">
                  <el-tag :type="getTagType(scope.row.isSignUpStore)">
                    {{ signUpTagText(scope.row.isSignUpStore) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="是否学员" prop="isSignUp" :filters="[
                { text: '已报名', value: '1' },
                { text: '未报名', value: '0' }
              ]" :filter-method="filterTag" filter-placement="bottom-end" v-if="columns[4].show" align="center">
                <template #default="scope">
                  <el-tag :type="getSignUpType(scope.row.isSignUp)">
                    {{ buildTagText(scope.row.isSignUp) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="vip状态" prop="isVip" :filters="[
                { text: '是', value: '1' },
                { text: '不是', value: '0' }
              ]" :filter-method="filterTag" filter-placement="bottom-end" v-if="columns[4].show" align="center">
                <template #default="scope">
                  <div v-if="scope.row.isVip === 1" style="display: flex;align-items: center;justify-content: center;">
                    <img src="https://image.lutongjiakao.com/system/05671c83615242d29f4d9997bee4a6d8.png" alt=""
                      style="width: 30px; height: 30px;margin-right: 5px;" />
                  </div>
                  <div v-else></div>
                </template>
              </el-table-column>
              <!-- 标签选项 -->
              <el-table-column label="来源渠道" prop="source" align="center">
                <template #default="scope">
                  <div>{{ scope.row.source === 'WECHAT' ? '微信小程序' : scope.row.source === 'APP' ? '应用' : scope.row.source
                    ===
                    'WEB' ? '后台添加' : '' }}</div>
                </template>
              </el-table-column>
              <el-table-column #default="scope" label="状态" align="center">
                <el-switch v-model="scope.row.state" :inactive-value="0" :active-value="1" class="custom-switch"
                  @change="editStatus(scope.row.id, scope.row.state)" />
              </el-table-column>
              <el-table-column label="标签" prop="tags" align="center" />
              <el-table-column label="注册时间" prop="registerTime" sortable v-if="columns[5].show" align="center" />
              <el-table-column label="最近活跃时间" prop="lastActiveTime" sortable v-if="columns[5].show" align="center" />
              <el-table-column fixed="right" label="操作" width="200px" align="center">
                <template #default="scope">
                  <el-tooltip class="box-item" effect="dark" content="练习记录" placement="top-start">
                    <button-table type="record" @click="openStudentsInfo(scope.row.id)" />
                  </el-tooltip>
                  <el-tooltip class="box-item" effect="dark" content="用户详情" placement="top-start">
                    <button-table type="edit" icon="&#xe689;" @click="linkuserdetails(scope.row.id)" />
                  </el-tooltip>
                  <el-tooltip class="box-item" effect="dark" content="删除用户" placement="top-start">
                    <button-table type="delete" @click="deleteUser(scope.row.id)" />
                  </el-tooltip>
                </template>
              </el-table-column>
            </template>
          </ArtTable>

          <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加用户' : '编辑用户'" width="30%"
            :close-on-click-modal="false">
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
              <el-form-item label="用户信息" prop="username">
                <el-input v-model="formData.username" />
              </el-form-item>
              <el-form-item label="用户id" prop="phone">
                <el-input v-model="formData.phone" />
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-select v-model="formData.sex">
                  <el-option label="男" value="男" />
                  <el-option label="女" value="女" />
                </el-select>
              </el-form-item>
              <el-form-item label="来源" prop="dep">
                <el-select v-model="formData.dep">
                  <el-option label="微信小程序" :value="1" />
                  <el-option label="IOS" :value="2" />
                  <el-option label="安卓" :value="3" />
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">提交</el-button>
              </div>
            </template>
          </el-dialog>
          <el-dialog v-model="userListDialogVisable" title="练习记录" width="1200" :before-close="handleCloseAddStudent"
            :close-on-click-modal="false">
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
              <el-tab-pane label="学习记录" name="0">
                <learnRecord></learnRecord>
              </el-tab-pane>
              <el-tab-pane label="模拟考试成绩" name="1">
                <simulateExam :simulatedExam="simulatedExam" :key="simulatedKey"></simulateExam>
              </el-tab-pane>
              <el-tab-pane label="考试记录" name="2">
                <examRecords></examRecords>
              </el-tab-pane>
            </el-tabs>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>


</template>

<script setup lang="ts">
import { ACCOUNT_TABLE_DATA } from '@/mock/temp/formData_userlist'
import { FormInstance } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { userList, EditUserList, userStatistics, practiceRecord, delMember } from '@/api/userStudentsApi'
import type { TabsPaneContext } from 'element-plus'
import learnRecord from './dialog/learnRecord.vue'
import simulateExam from './dialog/simulateExam.vue'
import examRecords from './dialog/examRecords.vue'
import CardList from './widget/CardList.vue'

const activeName = ref<string>('0')
const handleClick = (e: any) => {
  console.log(e.index)
}
const dialogType = ref('add')
const dialogVisible = ref(false)
const datavalue1 = ref('') //创建时间：
const datavalue2 = ref('') //最近活跃时间：
const router = useRouter() // 使用useRouter获取路由实例
const userListDialogVisable = ref(false)
const formData = reactive({
  username: '',
  phone: '',
  sex: '',
  dep: ''
})

const baomingOptions = [
  {
    value: '1',
    label: '已报名'
  },
  {
    value: '0',
    label: '未报名'
  }
]
const levelOptions = [
  {
    value: '1',
    label: '是'
  },
  {
    value: '0',
    label: ' 否'
  }
]

const columns = reactive([
  { name: '用户信息', show: true },
  { name: '手机号', show: true },
  { name: '性别', show: true },
  { name: '来源', show: true },
  { name: '状态', show: true },
  { name: '创建日期', show: true }
])

const searchFormRef = ref<FormInstance>()
const searchForm = reactive({
  name: '',
  phone: '',
  id: '',
  account: '',
  sex: '',
  level: '',
  creatStartTime: '',
  creatEndTime: '',
  activeStartTime: '',
  activeEndTime: '',
  queryApplyState: ''
})

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  datavalue1.value = ''
  datavalue2.value = ''
  searchForm.activeStartTime = ''
  searchForm.activeEndTime = ''
  searchForm.creatStartTime = ''
  searchForm.creatEndTime = ''
}

const tableData = ref([])
//编辑用户
// const showDialog = (type: string, row?: any) => {
//   dialogVisible.value = true
//   dialogType.value = type

//   if (type === 'edit' && row) {
//     formData.username = row.username
//     formData.phone = row.mobile
//     formData.sex = row.sex === 1 ? '男' : '女'
//     formData.dep = row.dep
//   } else {
//     formData.username = ''
//     formData.phone = ''
//     formData.sex = '男'
//     formData.dep = ''
//   }
// }
const linkuserdetails = function (id: number) {
  setTimeout(() => {
    router.push({
      path: '/user_student/UserDetails',
      query: {
        id
      }
    })
  }, 300)
}

const deleteUser = (id: string) => {
  ElMessageBox.confirm('确定删除该用户吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleDelMember(id)
  })
}

async function handleDelMember(id: string) {
  try {
    const res = await delMember(id)
    if (res.code === '00000') {
      ElMessage.success('删除成功')
      getData()
    }
  } catch {

  } finally {

  }
}

const filterTag = (value: string, row: any) => {
  return row.status === value
}

const getTagType = (status: string) => {
  return status === '1' ? 'primary' : 'info'
}

const getSignUpType = (status: number) => {
  return status === 1 ? 'primary' : 'info'
}

const buildTagText = (status: number) => {
  return status === 1 ? '是' : '否'
}

const signUpTagText = (status: string) => {
  return status === '1' ? '是' : '否'
}

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  dep: [{ required: true, message: '请选择来源', trigger: 'change' }]
})

const formRef = ref<FormInstance>()

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
      dialogVisible.value = false
    }
  })
}

const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}

const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
async function getData() {
  try {
    tableLoading.value = true
    const { code, data } = await userList(filterEmptyValues({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      queryStartTime: searchForm.creatStartTime ? formatDate(searchForm.creatStartTime) : '',
      queryEndTime: searchForm.creatEndTime ? formatDate(searchForm.creatEndTime) : '',
      queryName: searchForm.name,
      queryMobile: searchForm.phone,
      queryApplyState: searchForm.queryApplyState,
      queryIsVip: searchForm.level,
      queryStartActiveTime: searchForm.activeStartTime
        ? formatDate(searchForm.activeStartTime)
        : '',
      queryEndActiveTime: searchForm.activeEndTime ? formatDate(searchForm.activeEndTime) : ''
    }))
    if (code === '00000' && data) {
      tableData.value = data.list
      pageTotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}
const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}
const createTime = (e: any) => {
  if (e) {
    searchForm.creatStartTime = e[0]
    searchForm.creatEndTime = e[1]
  } else {
    searchForm.creatStartTime = ''
    searchForm.creatEndTime = ''
  }
  getData()
}
const activeTime = (e: any) => {
  if (e) {
    searchForm.activeStartTime = e[0]
    searchForm.activeEndTime = e[1]
  } else {
    searchForm.activeStartTime = ''
    searchForm.activeEndTime = ''
  }
  getData()
}
const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}

const simulatedExam = ref([])
const simulatedKey = ref(0)

const getLearnRecordData = async (id: string) => {
  const res = await practiceRecord({ memberId: id })
  if (res.code === '00000' && res.data) {
    simulatedExam.value = res.data.memberExamRecordList
    simulatedKey.value = new Date().getDate()
  }
}

function handleCloseAddStudent() {
  userListDialogVisable.value = false
}

const openStudentsInfo = (id: string) => {
  userListDialogVisable.value = true
  getLearnRecordData(id)
}
async function editStatus(id: number, state: number) {
  try {
    const res = await EditUserList({
      id,
      state
    })
    if (res.code === '00000') {
      if (state === 1) {
        ElMessage.error('拉黑用户成功')
      } else {
        ElMessage.success('恢复成功')
      }
    }
  } catch (e) {
  } finally {
    await getData()
  }
}

const homeLoading = ref(false)
const topData = ref({})
const topKey = ref(0)
const getHomePageData = async () => {
  try {
    homeLoading.value = true
    const res = await userStatistics();
    if (res.code === '00000') {
      topData.value = res.data ? res.data : {}
      topKey.value = new Date().getTime()
    }
  } catch {

  } finally {
    homeLoading.value = false
  }
}

onMounted(() => {
  getData()
  getHomePageData()
})
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;
  margin-top: 20px;

  .user {
    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 6px;
    }

    >div {
      margin-left: 10px;

      .user-name {
        font-weight: 500;
        color: var(--art-text-gray-800);
      }
    }
  }
}

.table-bar {
  padding: 0;
}

.column {
  display: flex;
  justify-content: space-between;
  margin-top: var(--console-margin);
  background-color: transparent !important;
}

/* 强制覆盖开关颜色 */
:deep(.custom-switch .el-switch__core) {
  background-color: #dcdfe6 !important;
  border-color: #dcdfe6 !important;
}

:deep(.custom-switch.is-checked .el-switch__core) {
  background-color: #ff4949 !important;
  border-color: #ff4949 !important;
}
</style>
